//
//  ViewPictureController.m
//  collection
//
//  Created by 张靖 on 2/7/12.
//  Copyright (c) 2012 Tsinghua University. All rights reserved.
//

#import "ViewPictureController.h"
#import "MBProgressHUDHelper.h"

@interface ViewPictureController()

@property (retain, nonatomic) IBOutlet UIScrollView *transparentView;
@property (retain, nonatomic) IBOutlet UILabel *numberIndicatorLabel;
@property (retain, nonatomic) IBOutlet UIButton *prevIndicatorButton;
@property (retain, nonatomic) IBOutlet UIButton *nextIndicatorButton;
@property (retain, nonatomic) IBOutlet UIButton *saveButton;
@property (retain, nonatomic) IBOutlet UIButton *fullScreenViewButton;
@property (retain, nonatomic) MBProgressHUD* indicatorView;
@property (nonatomic) int curIndex;

- (void)onClickView:(id)sender;
- (IBAction)onClickPrevImage:(id)sender;
- (IBAction)onClickNextImage:(id)sender;
- (IBAction)onClickSave:(id)sender;
- (IBAction)onClickFullScreenView:(id)sender;

- (void)gotoIndex:(int)index;

@end

@implementation ViewPictureController

@synthesize picArray = _picArray;
@synthesize transparentView = _transparentView;
@synthesize numberIndicatorLabel = _numberIndicatorLabel;
@synthesize prevIndicatorButton = _prevIndicatorButton;
@synthesize nextIndicatorButton = _nextIndicatorButton;
@synthesize saveButton = _saveButton;
@synthesize fullScreenViewButton = _fullScreenViewButton;
@synthesize indicatorView = _indicatorView;
@synthesize curIndex = _curIndex;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.curIndex = 0;
    }
    return self;
}


- (void)dealloc {
    
    self.transparentView = nil;
    self.indicatorView = nil;
    [_numberIndicatorLabel release];
    [_prevIndicatorButton release];
    [_nextIndicatorButton release];
    [_saveButton release];
    [_fullScreenViewButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib
    UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickView:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [self.transparentView addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    if (self.picArray != nil && [self.picArray count] > 0) {
        
        self.transparentView.contentSize = CGSizeMake(320 * [self.picArray count], 0);
        
        CGFloat ratio = self.transparentView.frame.size.height / self.transparentView.frame.size.width;
        
        for (int i = 0; i < [self.picArray count]; i++) {
            NSString* picName = [self.picArray objectAtIndex:i];
            UIImage* img = [UIImage imageNamed:picName];
            CGSize size = img.size;
            
            CGRect frame;
            if (size.height / size.width > ratio) {
                frame.size.height = self.transparentView.frame.size.height;
                frame.size.width = size.width * frame.size.height / size.height;
                frame.origin.x = i * self.transparentView.frame.size.width + (self.transparentView.frame.size.width - frame.size.width) / 2;
                frame.origin.y = 0;
            }
            else {
                frame.size.width = self.transparentView.frame.size.width;
                frame.size.height = size.height * frame.size.width / size.width;
                frame.origin.x = i * self.transparentView.frame.size.width;
                frame.origin.y = (self.transparentView.frame.size.height - frame.size.height) / 2;
            }
            
            UIImageView* view = [[UIImageView alloc] initWithFrame:frame];
            view.image = img;
            [self.transparentView addSubview:view];
            [view release];
        }
        
        [self gotoIndex:0];
    }
}

- (void)viewDidUnload
{
    [self setNumberIndicatorLabel:nil];
    [self setPrevIndicatorButton:nil];
    [self setNextIndicatorButton:nil];
    [self setSaveButton:nil];
    [self setFullScreenViewButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.transparentView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UIScrollViewDelegate]
/*
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
   
    CGPoint curPoint = scrollView.contentOffset;
    self.curIndex = curPoint.x / 320;
    
    [self gotoIndex:self.curIndex];
}
*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    CGPoint curPoint = scrollView.contentOffset;
    self.curIndex = curPoint.x / 320;
    
    [self gotoIndex:self.curIndex];
}

#pragma mark - [Private methods]

- (void)onClickView:(id)sender {
    
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)onClickPrevImage:(id)sender {
    if (self.curIndex == 0) {
        return;
    }
    
    self.curIndex--;
    
    [self gotoIndex:self.curIndex];
}

- (IBAction)onClickNextImage:(id)sender {
    if (self.curIndex == self.picArray.count - 1) {
        return;
    }
    
    self.curIndex++;
    
    [self gotoIndex:self.curIndex];
}

- (IBAction)onClickSave:(id)sender {
    
    if (self.curIndex < 0 || self.curIndex >= self.picArray.count) {
        return;
    }
    
    UIImage* curImage = [self.picArray objectAtIndex:self.curIndex];
    if (curImage == nil) {
        return;
    }
    
    UIImageWriteToSavedPhotosAlbum(curImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (IBAction)onClickFullScreenView:(id)sender {
}

- (void)gotoIndex:(int)index {
    
    if (self.picArray == nil || 
        self.picArray.count == 0 ||
        index >= self.picArray.count) {
        
        return;
    }
    
    CGPoint point = CGPointMake(320 * index, 0);
    [self.transparentView setContentOffset:point animated:YES];
    
    self.curIndex = index;
    self.numberIndicatorLabel.text = [NSString stringWithFormat:@"%d/%d", self.curIndex + 1, self.picArray.count];
    self.prevIndicatorButton.enabled = (self.curIndex > 0);
    self.nextIndicatorButton.enabled = (self.curIndex < self.picArray.count - 1);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (self.indicatorView == nil) {
        self.indicatorView = [MBProgressHUDHelper popUpMBProcessHUD:self.view delegate:nil];
    }
    
    if (error != nil) 
    {
        [MBProgressHUDHelper changeToMBFailedMode:self.indicatorView customMsg:@"保存未成功" afterDelay:1.2f];
    }
    else 
    {
        [MBProgressHUDHelper changeToMBSuccessMode:self.indicatorView customMsg:@"保存至相册" afterDelay:1.2f];
    }
}

@end
